import { _decorator, Component, EventTouch, Node, NodeEventType, UITransform, Vec2, Vec3 } from 'cc';
const { ccclass, property } = _decorator;
const INIT_POS = new Vec3(0, 0, 0)
const BASE_RADIUS = 75
@ccclass('BattleJoyStick')
export class BattleJoyStick extends Component {
    Body: Node
    Stick: Node
    input: Vec2 = Vec2.ZERO
    uiTransform: UITransform
    start() {
        this.Body = this.node.getChildByName('Body')
        this.Stick = this.Body.getChildByName('Stick')
        this.Body.setPosition(INIT_POS)
        this.Body.active = false
        this.uiTransform = this.node.getComponent(UITransform)

        this.node.on(NodeEventType.TOUCH_START, this.touchStart, this)
        this.node.on(NodeEventType.TOUCH_MOVE, this.touchMove, this)
        this.node.on(NodeEventType.TOUCH_END, this.touchEnd, this)
        this.node.on(NodeEventType.TOUCH_CANCEL, this.touchEnd, this)
    }

    onDestroy() {

        this.node.off(NodeEventType.TOUCH_START, this.touchStart, this)
        this.node.off(NodeEventType.TOUCH_MOVE, this.touchMove, this)
        this.node.off(NodeEventType.TOUCH_END, this.touchEnd, this)
        this.node.off(NodeEventType.TOUCH_CANCEL, this.touchEnd, this)
    }

    touchStart(e: EventTouch) {
        const pos = e.getUILocation()
        this.Body.setPosition(pos.x - this.uiTransform.width / 2, pos.y - this.uiTransform.height / 2)
        this.Body.active = true

    }
    touchMove(e: EventTouch) {
        const touchPos = new Vec2(
            e.getUILocation().x - this.Body.getPosition().x - this.uiTransform.width / 2,
            e.getUILocation().y - this.Body.getPosition().y - this.uiTransform.height / 2
        )
        if (touchPos.length() > BASE_RADIUS) {
            touchPos.multiplyScalar(BASE_RADIUS / touchPos.length())
        }
        this.Stick.setPosition(touchPos.x, touchPos.y)
        this.input = touchPos.normalize()
    }
    touchEnd() {
        this.Body.setPosition(INIT_POS)
        this.Stick.setPosition(0, 0)
        this.input = Vec2.ZERO
        this.Body.active = false
    }
}